#include <iostream>
#include <unistd.h>
#include "Thread.hpp"
using namespace std;

typedef CPThread<int> CPT;

void* consumer(void* args) //消费者
{
    CPT* cpt = static_cast<CPT*>(args);
    while(true)
    {
        usleep(2000);
        int data = 0;
        cpt->pop(data);
        cout<<pthread_self()<<" | 消费者: "<<data<<endl;
    }

    return nullptr;
}

void* producer(void* args) //生产者
{
    CPT* cpt = static_cast<CPT*>(args);
    while(true)
    {
        usleep(1000);
        int data = rand()%(1000^31)+1;
        cpt->push(data);
        cout<<pthread_self()<<" | 生产者: "<<data<<endl;
        //cout<<cpt->getsize()<<endl;
    }

    return nullptr;
}


int main()
{
    int n = 10; //商品数量最大值
    srand(time(nullptr)^getpid());
    CPT cpt(n);
    pthread_t p[5],c[2]; //生产者消费者线程
    int pn = 5;
    int cn = 2;
    for(int i = 0;i<pn;++i)
    {
        pthread_create(p+i,nullptr,producer,(void*)(&cpt));
    }
    for(int i = 0;i<cn;++i)
    {
        pthread_create(c+i,nullptr,consumer,(void*)(&cpt));
    }

    for(int i = 0;i<cn;++i)
    {
        pthread_join(c[i],nullptr);
    }
    for(int i = 0;i<pn;++i)
    {
        pthread_join(p[i],nullptr);
    }

    return 0;
}